/**
 * http://usejsdoc.org/ npm install log4js, jsonfile
 */
var log4js = require('log4js');
var jsonfile = require('jsonfile');
var category;
var message = "../config/message.json";
log4js.configure("../config/log4js.json",[])

var errlogger = log4js.getLogger("error");
var debuglogger = log4js.getLogger("debug");
var tracelogger = log4js.getLogger("trace");

String.prototype.format = function(args) {
    var s = this;
    if (args &&　typeof (args) == "object" && !isNaN(args.length)) {
        for (var i = 0; i < args.length; i++) {
        	s=s.replace(new RegExp("({)" + i + "(})", "g"), args[i]);
        }
    } else if (args) {
    	s=s.replace(new RegExp("({)0(})", "g"), args);
    }
    return s.toString();
};

var messagedata = jsonfile.readFileSync(message);
var logMsg = function (level, msgCode, msgParam) {
	if (!msgCode) {
	  errlogger.error(msgCode + " No Exists");
	}
	msgCode = msgCode || "";
	msgParam = msgParam || "";

	var msg = messagedata[msgCode] || msgCode;
	var outmsg = msg.format(msgParam);


	switch (level) {
	case "trace":
	  tracelogger.trace(outmsg);
		break;
	case "debug":
	  debuglogger.debug(outmsg);
		break;
	case "info":
	  debuglogger.info(outmsg);
		break;
	case "warn":
	  debuglogger.warn(outmsg);
		break;
	case "error":
	  errlogger.error(outmsg);
		break;
	case "fatal":
	  errlogger.fatal(outmsg);
		break;
	}
}
var myLogger = {
//		setCategory:function(category){
//			logger = log4js.getLogger(category);
//		},
		trace:function(msgCode, msgParam){
			logMsg("trace", msgCode, msgParam);
		},
		debug:function(msgCode, msgParam){
			logMsg("debug", msgCode, msgParam);
		},
		info:function(msgCode, msgParam){
			logMsg("info", msgCode, msgParam);
		},
		warn:function(msgCode, msgParam){
			logMsg("warn", msgCode, msgParam);
		},
		error:function(msgCode, msgParam){
			logMsg("error", msgCode, msgParam);
		},
		fatal:function(msgCode, msgParam){
			logMsg("fatal", msgCode, msgParam);
		}
}

module.exports= myLogger